<template>
  <!-- 导出模板文件按钮 -->
  <span>
    <a-button
      v-if="!custom"
      v-bind="$attrs"
      :type="buttonType"
      :icon="icon"
      :disabled="disabled"
      v-on="$listeners"
      @click="downFile"
    >{{ buttonText }}</a-button>
    <!-- 插槽 -->
    <slot
      v-else
      :downFile="downFile"
    />
  </span>
</template>

<script>
import { templatesDownloadUrl } from '@/config'

export default {
  inheritAttrs: false,
  name: 'ExportMould',
  props: {
    // 导出模板按钮文本
    buttonText: {
      type: String,
      default: () => '导出模板',
    },
    // 导出按钮类型
    buttonType: {
      type: String,
      default: () => 'primary',
    },
    // 导出按钮图标
    icon: {
      type: String,
      default: () => '',
    },
    // 自定义上传容器
    custom: {
      type: Boolean,
      default: () => false,
    },
    // 禁用状态
    disabled: {
      type: Boolean,
      default: () => false,
    },
    // 文件code
    templateCode: {
      type: String,
      default: () => '',
    },
    // 下载地址
    // hostUrl: {
    //   type: String,
    //   default: () => process.env.VUE_APP_templatesDownloadUrl,
    // },
  },
  data() {
    return {
      hostUrl: templatesDownloadUrl,
    }
  },
  methods: {
    /**
     * 下载模板
     */
    downFile() {
      if (!this.templateCode) {
        this.$message.warning('缺少文件编码')
        return
      }
      let api = this.hostUrl + this.templateCode
      // fetch(api, {
      //   method: 'get',
      //   responseType: 'blob',
      // })
      //   .then((res) => {
      //     return res.blob()
      //   })
      //   .then((response) => {
      //     const url = window.URL.createObjectURL(new Blob([response]))
      const link = document.createElement('a')
      link.href = api
      // link.setAttribute('target', '_blank')
      link.setAttribute('target', '_self')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      // })
    },
  },
}
</script>